package com.example.translateappjava.Utils; // 你的包名

import android.app.Activity;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.example.translateappjava.Fragment.HomeFragment;
import com.example.translateappjava.Listener.LoadingProgressListener;
import com.example.translateappjava.Service.AliyunAPI.AliyunAPIHelper;
import com.example.translateappjava.Service.DiabetesFoodAdvisor;
import com.example.translateappjava.Service.Doubao.DoubaoVisionHelper;
import com.example.translateappjava.Service.YOLOAPI.ImageUploader;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class ImageRecognitionManager {

    private Activity activity;
    private DoubaoVisionHelper doubaoVisionHelper;
    private ArrayList<ImageData> imageDataList;
    private AtomicInteger remainingRequests;
    private RecognitionCompleteListener recognitionCompleteListener;
    private DiabetesFoodAdvisor diabetesFoodAdvisor;
    private LoadingProgressListener loadingProgressListener;

    public interface RecognitionCompleteListener {
        void onRecognitionComplete(ArrayList<ImageData> imageDataList);
    }

    public ImageRecognitionManager(HomeFragment fragment, Activity activity) {
        this.activity = activity;

        this.doubaoVisionHelper = new DoubaoVisionHelper(activity);
        if (fragment instanceof DoubaoVisionHelper.DoubaoVisionListener) {
            this.doubaoVisionHelper.setDoubaoVisionListener((DoubaoVisionHelper.DoubaoVisionListener) fragment);
        } else {
            Log.e("ImageRecognitionManager", "HomeFragment must implement DoubaoVisionListener");
        }

        this.diabetesFoodAdvisor = new DiabetesFoodAdvisor(activity);
    }

    public void setLoadingProgressListener(LoadingProgressListener listener) {
        this.loadingProgressListener = listener;
        if (this.diabetesFoodAdvisor != null) {
            this.diabetesFoodAdvisor.setLoadingProgressListener(listener);
        }
    }

    public void setRecognitionCompleteListener(RecognitionCompleteListener listener) {
        this.recognitionCompleteListener = listener;
    }

    public void processImage(Bitmap bitmap) {
        if (loadingProgressListener != null) {
            loadingProgressListener.onProgressUpdate("上传图片进行分割...");
        }

        ImageUploader uploader = new ImageUploader();
        if (this.loadingProgressListener != null) {
            uploader.setLoadingProgressListener(this.loadingProgressListener);
        }

        uploader.uploadImage(bitmap, new ImageUploader.ImageUploadCallback() {
            @Override
            public void onUploadComplete(ArrayList<Bitmap> bitmaps, ArrayList<byte[]> bytes, ArrayList<String> URLs) {
                Log.v("ImageRecognitionManager", "YOLO分割完成，得到图像块数量: " + (bitmaps != null ? bitmaps.size() : 0));

                if (bitmaps == null || bitmaps.isEmpty()) {
                    Log.w("ImageRecognitionManager", "YOLO未分割出任何图像块。");
                    activity.runOnUiThread(() -> Toast.makeText(activity, "未能从图片中检测到物体。", Toast.LENGTH_SHORT).show());
                    if (loadingProgressListener != null) {
                        Log.i("onProcessingComplete", "YOLO未分割出任何图像块");
                        loadingProgressListener.onProcessingComplete();
                    }
                    return;
                }

                if (loadingProgressListener != null) {
                    loadingProgressListener.onProgressUpdate("分割完成，开始识别图像块...", "共 " + bitmaps.size() + " 个");
                }

                remainingRequests = new AtomicInteger(bitmaps.size());
                imageDataList = new ArrayList<>();

                for (int i = 0; i < bitmaps.size(); i++) {
                    ImageData imageData = new ImageData(bitmaps.get(i), "待识别", null, false);
                    if (URLs != null && i < URLs.size() && URLs.get(i) != null) {
                        imageData.setImageURL(URLs.get(i));
                    } else {
                        Log.w("ImageRecognitionManager", "URL for image at index " + i + " is null, URLs list might be short, or URL itself is null.");
                        imageData.setImageURL("URL_UNAVAILABLE");
                    }
                    imageDataList.add(imageData);
                }
                startAliyunRecognition(bytes);
            }

            @Override
            public void onUploadFailed(Exception e) {
                Log.e("ImageRecognitionManager", "YOLO图片上传/分割失败: " + e.getMessage(), e);
                activity.runOnUiThread(() -> Toast.makeText(activity, "图片分割处理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                if (loadingProgressListener != null) {
                    loadingProgressListener.onProcessingError("图片分割失败");
                }
            }
        });
    }

    private void startAliyunRecognition(ArrayList<byte[]> bytesList) {
        if (bytesList == null || bytesList.isEmpty()) {
            Log.w("ImageRecognitionManager", "没有图像数据可供阿里云识别。");
            if (remainingRequests != null && remainingRequests.get() == 0) {
                processAllRecognitionComplete();
            } else if (remainingRequests == null && (imageDataList == null || imageDataList.isEmpty())) {
                processAllRecognitionComplete();
            }
            return;
        }

        AliyunAPIHelper aliyunAPIHelper = new AliyunAPIHelper(activity);
        aliyunAPIHelper.setAliyunAPIListener(new AliyunAPIHelper.AliyunAPIListener() {
            @Override
            public void AliyunAPIResponse(String response, int index) {
                handleAliyunAPIResponse(response, index);
            }

            @Override
            public void AliyunAPIError(String message) {
                Log.e("ImageRecognitionManager", "阿里云API错误(整体): " + message);
                if (remainingRequests != null) {
                    int currentlyRemaining = remainingRequests.getAndSet(0); // Set to 0 and get old value
                    // Mark all corresponding imageData as failed if not already processed
                    if (imageDataList != null) {
                        for(int i=0; i < imageDataList.size(); i++){
                            // A more robust way would be to check a status flag on ImageData
                            // For simplicity, if we get a global error, we might assume unprocessed ones failed
                            // This part needs careful consideration based on how AliyunAPIError is triggered
                        }
                    }
                }
                if (loadingProgressListener != null) {
                    loadingProgressListener.onProcessingError("阿里云识别服务出错");
                } else {
                    activity.runOnUiThread(() -> Toast.makeText(activity, "阿里云识别出错", Toast.LENGTH_SHORT).show());
                }
                processAllRecognitionComplete();
            }
        });

        int numberOfRequests = Math.min(bytesList.size(), (imageDataList != null ? imageDataList.size() : 0));
        if (bytesList.size() != (imageDataList != null ? imageDataList.size() : 0)) {
            Log.w("ImageRecognitionManager", "Byte array count (" + bytesList.size() + ") does not match imageDataList count (" + (imageDataList != null ? imageDataList.size() : 0) + "). Using minimum for requests.");
        }
        if (imageDataList == null) {
            Log.e("ImageRecognitionManager", "imageDataList is null before starting Aliyun recognition. Aborting.");
            processAllRecognitionComplete();
            return;
        }

        for (int i = 0; i < numberOfRequests; i++) {
            if (loadingProgressListener != null) {
                int totalItems = imageDataList.size();
                // remainingRequests might not be fully accurate here if some are already delegated to Doubao
                // A better way to count processed items might be needed if strict progress is essential
                int processedOrDelegated = totalItems - (remainingRequests != null ? remainingRequests.get() : 0);
                loadingProgressListener.onProgressUpdate("正在识别物体 (" + (processedOrDelegated + 1) + "/" + totalItems + ")");
            }
            if (bytesList.get(i) != null) {
                aliyunAPIHelper.AliyunAPIFilePathRequest(bytesList.get(i), i);
            } else {
                Log.e("ImageRecognitionManager", "Byte array at index " + i + " is null. Skipping Aliyun request for this item.");
                if (indexIsValid(i)) {
                    imageDataList.get(i).setRecognitionResult("识别失败(数据错误)");
                }
                if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                    processAllRecognitionComplete();
                }
            }
        }
        if (numberOfRequests == 0 && imageDataList != null && !imageDataList.isEmpty() && remainingRequests != null && remainingRequests.get() > 0) {
            Log.w("ImageRecognitionManager", "No valid byte arrays to send to Aliyun, but imageDataList exists. Completing.");
            remainingRequests.set(0); // Mark all as processed for completion
            processAllRecognitionComplete();
        } else if (numberOfRequests == 0 && (imageDataList == null || imageDataList.isEmpty())) {
            processAllRecognitionComplete();
        }
    }

    private boolean indexIsValid(int index) {
        return imageDataList != null && index >= 0 && index < imageDataList.size();
    }

    public void handleAliyunAPIResponse(String response, int index) {
        Log.d("ImageRecognitionManager", "阿里云响应 (索引 " + index + "): " + response);
        if (!indexIsValid(index)) {
            Log.e("ImageRecognitionManager", "阿里云响应索引越界或imageDataList为空: " + index);
            if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                processAllRecognitionComplete();
            }
            return;
        }

        ImageData currentImageData = imageDataList.get(index);

        // 修改点：如果阿里云返回 "没调用到" 或 "非菜"，都转豆包
        if ("非菜".equals(response) || "没调用到".equals(response)) {
            String reasonForDoubao = "非菜".equals(response) ? "非菜" : "阿里云未有效调用";
            Log.i("ImageRecognitionManager", "阿里云初步判断为'" + reasonForDoubao + "' (索引 " + index + "), 转豆包二次识别");
            if (loadingProgressListener != null) {
                loadingProgressListener.onProgressUpdate("物体 " + (index + 1) + " 初步识别为" + reasonForDoubao + "，尝试精细识别...");
            }
            Bitmap bitmapToAnalyze = currentImageData.getImage();
            if (doubaoVisionHelper != null && bitmapToAnalyze != null) {
                doubaoVisionHelper.analyzeFood(bitmapToAnalyze, index); // 豆包的回调会处理remainingRequests
            } else {
                Log.w("ImageRecognitionManager", "无法进行二次识别 (索引 " + index + "): Doubao helper or bitmap is null.");
                currentImageData.setRecognitionResult("识别失败(" + reasonForDoubao + ")");
                if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                    processAllRecognitionComplete();
                }
            }
        } else {
            currentImageData.setRecognitionResult(response);
            if (loadingProgressListener != null) {
                loadingProgressListener.onProgressUpdate("物体 " + (index + 1) + " 识别为: " + response);
            }
            if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                processAllRecognitionComplete();
            }
        }
    }


    public void handleAliyunAPIError(String message) {
        Log.e("ImageRecognitionManager", "Aliyun API Error: " + message);

        if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
            processAllRecognitionComplete();
        }
    }
    public void handleDoubaoVisionResponse(String response, int index) {
        Log.d("ImageRecognitionManager", "豆包二次识别响应 (索引 " + index + "): " + response);
        activity.runOnUiThread(() -> {
            if (!indexIsValid(index)) {
                Log.e("ImageRecognitionManager", "豆包响应索引越界或imageDataList为空: " + index);
                if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                    processAllRecognitionComplete();
                }
                return;
            }

            ImageData currentImageData = imageDataList.get(index);
            if (response.contains("无食物") || response.contains("没有食物") || response.contains("非食物")) {
                currentImageData.setRecognitionResult("非食物"); // 统一标记，方便后续过滤
                Toast.makeText(activity, "物体 " + (index + 1) + " 精细识别结果：非食物", Toast.LENGTH_SHORT).show();
            } else {
                currentImageData.setRecognitionResult(response);
                if (loadingProgressListener != null) {
                    loadingProgressListener.onProgressUpdate("物体 " + (index + 1) + " 精细识别为: " + response);
                }
            }

            if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                processAllRecognitionComplete();
            }
        });
    }

    public void handleDoubaoVisionError(String error, int index) {
        Log.e("ImageRecognitionManager", "豆包二次识别错误 (索引 " + index + "): " + error);
        activity.runOnUiThread(() -> {
            if (indexIsValid(index)) {
                imageDataList.get(index).setRecognitionResult("识别失败(豆包)");
            } else {
                Log.e("ImageRecognitionManager", "豆包错误索引越界或imageDataList为空: " + index);
            }
            Toast.makeText(activity, "物体 " + (index + 1) + " 精细识别失败", Toast.LENGTH_SHORT).show();
            if (remainingRequests != null && remainingRequests.decrementAndGet() == 0) {
                processAllRecognitionComplete();
            }
        });
    }

    private void processAllRecognitionComplete() {
        Log.d("ImageRecognitionManager", "所有识别请求（阿里云/豆包）处理完毕。准备过滤和最终处理...");

        if (imageDataList == null || imageDataList.isEmpty()) {
            Log.w("ImageRecognitionManager", "原始imageDataList在完成时为空或null。");
            activity.runOnUiThread(() -> Toast.makeText(activity, "图像识别流程未产生有效数据。", Toast.LENGTH_SHORT).show());
            if (loadingProgressListener != null) {
                loadingProgressListener.onProcessingComplete();
            }
            if (recognitionCompleteListener != null) {
                recognitionCompleteListener.onRecognitionComplete(new ArrayList<>());
            }
            return;
        }

        // 过滤原始imageDataList，移除包含“无食物”、“没有食物”、“非食物”的结果
        ArrayList<ImageData> finalProcessableList = new ArrayList<>();
        for (ImageData data : imageDataList) {
            String result = data.getRecognitionResult();
            boolean toBeRemoved = result != null &&
                    (result.contains("无食物") ||
                            result.contains("没有食物") ||
                            result.contains("非食物"));
            if (!toBeRemoved) {
                finalProcessableList.add(data);
            } else {
                Log.i("ImageRecognitionManager", "从最终列表中移除条目，结果: '" + result + "'");
            }
        }

        Log.d("ImageRecognitionManager", "原始列表大小: " + imageDataList.size() + ", 过滤后列表大小: " + finalProcessableList.size());

        if (!finalProcessableList.isEmpty()) {
            ArrayList<ImageData> listForGpt = new ArrayList<>();
            for (ImageData data : finalProcessableList) {
                // isValidRecognitionResult 用于判断是否送GPT，它内部已经排除了"无食物"等
                if (isValidRecognitionResult(data.getRecognitionResult())) {
                    listForGpt.add(data);
                }
            }

            Log.d("ImageRecognitionManager", "准备送往GPT分析的条目数量: " + listForGpt.size());

            if (!listForGpt.isEmpty()) {
                if (loadingProgressListener != null) {
                    loadingProgressListener.onProgressUpdate("识别完成，开始营养分析...");
                }
                if (diabetesFoodAdvisor != null) {
                    diabetesFoodAdvisor.processFoodRecognitionResult(new ArrayList<>(listForGpt)); // 传递给GPT的是进一步筛选过的
                } else {
                    Log.e("ImageRecognitionManager", "DiabetesFoodAdvisor is null, cannot process for GPT.");
                    activity.runOnUiThread(() -> Toast.makeText(activity, "营养分析服务未初始化", Toast.LENGTH_LONG).show());
                    if (loadingProgressListener != null) {
                        loadingProgressListener.onProcessingError("营养分析服务错误");
                    }
                }
            } else { // finalProcessableList 不为空，但没有有效项送GPT
                Log.w("ImageRecognitionManager", "过滤后的列表中没有有效的识别结果可供GPT分析。");
                activity.runOnUiThread(() -> Toast.makeText(activity, "未能识别出可进行营养分析的食物。", Toast.LENGTH_LONG).show());
                if (loadingProgressListener != null) {
                    Log.i("onProcessingComplete", "过滤后没有东西给GPT，直接完成");
                    loadingProgressListener.onProcessingComplete(); // 结束加载
                }
            }
            // 回调的是过滤后的 finalProcessableList
            if (recognitionCompleteListener != null) {
                recognitionCompleteListener.onRecognitionComplete(new ArrayList<>(finalProcessableList));
            }

        } else { // finalProcessableList (过滤后) 为空
            Log.w("ImageRecognitionManager", "识别流程结束，过滤后列表为空。");
            activity.runOnUiThread(() -> Toast.makeText(activity, "未能识别出任何有效物体。", Toast.LENGTH_SHORT).show());
            if (loadingProgressListener != null) {
                Log.i("onProcessingComplete", "过滤后列表为空");
                loadingProgressListener.onProcessingComplete();
            }
            if (recognitionCompleteListener != null) {
                recognitionCompleteListener.onRecognitionComplete(new ArrayList<>());
            }
        }
    }

    private boolean isValidRecognitionResult(String result) {
        // 此方法用于判断一个识别结果是否适合进行GPT分析
        // 它已经排除了“无食物”、“非食物”、“识别失败”等
        return result != null &&
                !result.equals("待识别") &&
                !result.equalsIgnoreCase("null") &&
                !result.contains("无食物") &&
                !result.contains("没有食物") &&
                !result.contains("非食物") &&
                !result.contains("识别失败");
    }
}